package com.stm.bi.report;

import com.stm.base.api.RegionRemoteService;
import com.stm.base.dto.query.RegionListQry;
import com.stm.base.dto.vo.RegionVO;
import com.stm.bi.dto.query.RegionalSaleQry;
import com.stm.bi.dto.query.RegionalSaleQuery;
import com.stm.bi.model.Chart;
import com.stm.framework.core.util.FileResourceLoader;
import com.stm.framework.core.util.SpringContextUtil;
import com.stm.framework.dbcp.JdbcService;
import com.stm.framework.dto.Response;
import com.stm.ucenter.api.BizCustomerRemoteService;
import com.stm.ucenter.dto.query.BizCustomerListQry;
import com.stm.ucenter.dto.vo.BizCustomerVO;
import jakarta.annotation.Resource;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDate;
import java.util.*;
import java.util.stream.Collectors;


/**
 * @author zp
 * @date 2025/2/14 9:09
 */
@Component
public class RegionalTurnoverMapQueryExe extends AbsChartQueryExe<RegionalSaleQuery, Chart> {
    @Resource
    private JdbcService jdbcService;

    @Resource
    private BizCustomerRemoteService bizCustomerRemoteService;
    @Resource
    private RegionRemoteService regionRemoteService;


    @Override
    public Chart query(Long orgId, String orgNo, RegionalSaleQuery regionalSaleQry) {
        Chart chart = new Chart();
        List<String> items = chart.getItems();
        items.add("区域成交量");
        List<List<Object>> datas = new ArrayList<>();
        // 根据部门id查询该部门下所有B端客户信息
        BizCustomerListQry bizQry = new BizCustomerListQry();
        bizQry.setChildId(regionalSaleQry.getDeptId());
        Response<List<BizCustomerVO>> bizResponse = bizCustomerRemoteService.selectList(bizQry);
        if (!bizResponse.isSuccess() || bizResponse.getData().isEmpty()) {
            return chart;
        }
        List<BizCustomerVO> bizCustomers = bizResponse.get();
        List<String> bizCodes = bizCustomers.stream().map(BizCustomerVO::getCode).filter(Objects::nonNull).collect(Collectors.toList());
        // 获取所有省份
        RegionListQry regionListQry = new RegionListQry();
        regionListQry.setType(2);
        Response<List<RegionVO>> regionResponse = regionRemoteService.selectList(regionListQry);
        if (!regionResponse.isSuccess() || regionResponse.getData().isEmpty()) {
            return chart;
        }
        List<RegionVO> regionList = regionResponse.getData();

        List<Map> maps = getToBCustomerList(bizCustomers, bizCodes,orgId);
        // 默认展示数据
        if (maps.isEmpty()) {
            for (RegionVO region : regionList) {
                // 销量、占比、
                List<Object> data = new ArrayList<>();
                String name = region.getName();
                if (region.getId().equals(820000000000L)) {
                    name = "澳门特别行政区";
                } else if (region.getId().equals(810000000000L)) {
                    name = "香港特别行政区";
                }
                data.add(name);
                data.add(BigDecimal.ZERO);
                data.add(BigDecimal.ZERO);
                data.add(region.getId());
                datas.add(data);
            }
            chart.setDatas(datas);
            return chart;
        }
        Map<String, BigDecimal> provinceTotalQtyMap = maps.stream()
                .collect(Collectors.groupingBy(
                        m -> ((Long) m.get("provinceCode")).toString(),
                        Collectors.reducing(
                                BigDecimal.ZERO,
                                m -> (BigDecimal) m.get("number_of_dealing"),
                                BigDecimal::add
                        )
                ));
        // 按销量倒序排序
        provinceTotalQtyMap = provinceTotalQtyMap.entrySet().stream()
                .sorted(Map.Entry.<String, BigDecimal>comparingByValue().reversed())
                .collect(Collectors.toMap(
                        Map.Entry::getKey,
                        Map.Entry::getValue,
                        (oldValue, newValue) -> oldValue,
                        LinkedHashMap::new
                ));
        // 计算省份销量阶梯
        int size = provinceTotalQtyMap.size();
        int phaseOne = (int) Math.round(size * 0.1);
        int phaseTwo = (int) Math.round(size * 0.2);
        int phaseThree = (int) Math.round(size * 0.3);
        int phaseOneNum = 0;
        int phaseTwoNum = 0;
        int phaseThreeNum = 0;
        List<Integer> lowerLimit = new ArrayList<>();
        // 按照阶梯截取map得到销量区间
        List<String> strings = new ArrayList<>(provinceTotalQtyMap.keySet());
        for (int i = 0; i < size; i++) {

            BigDecimal value = provinceTotalQtyMap.get(strings.get(i));
            int integerPartLength = getIntegerPartLength(value);
            int roundedValue = 0;
            // 取千分位并四舍五入
            if (integerPartLength == 6) {
                roundedValue = value.divide(new BigDecimal("100000"), 0, RoundingMode.HALF_UP).multiply(new BigDecimal("100000")).intValue();
            } else if (integerPartLength == 5) {
                roundedValue = value.divide(new BigDecimal("10000"), 0, RoundingMode.HALF_UP).multiply(new BigDecimal("10000")).intValue();
            } else if (integerPartLength == 4) {
                roundedValue = value.divide(new BigDecimal("1000"), 0, RoundingMode.HALF_UP).multiply(new BigDecimal("1000")).intValue();
            } else if (integerPartLength == 3) {
                roundedValue = value.divide(new BigDecimal("100"), 0, RoundingMode.HALF_UP).multiply(new BigDecimal("100")).intValue();
            } else if (integerPartLength == 2) {
                roundedValue = value.divide(new BigDecimal("10"), 0, RoundingMode.HALF_UP).multiply(new BigDecimal("10")).intValue();
            }

            if (i < phaseOne) {
                if (phaseOneNum == 0) {
                    phaseOneNum = roundedValue;
                } else if (phaseOneNum > roundedValue) {
                    phaseOneNum = roundedValue;
                }
            } else if (i < phaseOne + phaseTwo) {
                if (phaseTwoNum == 0) {
                    phaseTwoNum = roundedValue;
                } else if (phaseTwoNum > roundedValue) {
                    phaseTwoNum = roundedValue;
                }
            } else if (i < phaseOne + phaseTwo + phaseThree) {
                if (phaseThreeNum == 0) {
                    phaseThreeNum = roundedValue;
                } else if (phaseThreeNum > roundedValue) {
                    phaseThreeNum = roundedValue;
                }
            }
            lowerLimit.add(roundedValue);
        }
        // 如果数量小于3
        if (size == 3){
            phaseOneNum = lowerLimit.get(0);
            phaseTwoNum = lowerLimit.get(1);
            phaseThreeNum = lowerLimit.get(2);
        }else if (size == 2){
            // 只有两个数据在第二和第三个区间
            phaseOneNum = lowerLimit.get(0) + 1000;
            phaseTwoNum = lowerLimit.get(0) ;
            phaseThreeNum = lowerLimit.get(1);
        }else if (size == 1){
            // 只有一个数据，数据值都一样，比源数据小一点
            phaseOneNum = lowerLimit.get(0) + 1000;
            phaseTwoNum = lowerLimit.get(0) + 1000;
            phaseThreeNum = lowerLimit.get(0) + 1000;
        }
        chart.setName(phaseOneNum + "," + phaseTwoNum + "," + phaseThreeNum + "," + phaseThreeNum);

        //总销量
        double totalQty = maps.stream().map(m -> (BigDecimal) m.get("number_of_dealing")).filter(Objects::nonNull).mapToDouble(BigDecimal::doubleValue).sum();
        // 给所有省份赋值
        for (RegionVO region : regionList) {
            // 销量、占比、
            List<Object> data = new ArrayList<>();
            String name = region.getName();
            if (region.getId().equals(820000000000L)) {
                name = "澳门特别行政区";
            } else if (region.getId().equals(810000000000L)) {
                name = "香港特别行政区";
            }
            data.add(name);
            if (provinceTotalQtyMap.keySet().stream().noneMatch(e -> e.equals(region.getId().toString()))) {
                data.add(BigDecimal.ZERO);
                data.add(BigDecimal.ZERO);
            } else {
                BigDecimal qty = provinceTotalQtyMap.get(region.getId().toString());
                data.add(qty);
                if (totalQty != 0.0) {
                    data.add(BigDecimal.valueOf(100 * qty.doubleValue() / totalQty).setScale(2, RoundingMode.HALF_UP));
                }
            }
            data.add(region.getId());
            datas.add(data);
        }

        chart.setDatas(datas);
        return chart;

    }

    public List<Map> getToBCustomerList(List<BizCustomerVO> bizCustomers,List<String> bizCodes, Long orgId) {
        // 查全部
        String year = String.valueOf(LocalDate.now().getYear());
        StringBuilder sql = new StringBuilder();
        sql.append("SELECT * FROM ads_base_biz_customer WHERE  org_id = ")
                .append(orgId)
                .append(" and year = ")
                .append(year);
        if (ObjectUtils.isNotEmpty(bizCodes)){
            sql.append(" and customer_code in (");
            for (String bizCode : bizCodes) {
                sql.append("\"")
                        .append(bizCode)
                        .append("\"")
                        .append(",");
            }
            sql.deleteCharAt(sql.length() - 1);
            sql.append(")");
        }
//        sql.append("group by customer_id ORDER BY number_of_dealing");
        List<Map> maps = jdbcService.selectList(sql.toString(), new Object[]{});

        // 给map赋值省份id、省份名称、客户类型和合作类型、新老客
        if (ObjectUtils.isNotEmpty(bizCustomers)) {
            for (Map map : maps) {
                bizCustomers.stream().filter(e -> e.getCode().equals(map.get("customer_code"))).findFirst().ifPresent(biz -> {
                    map.put("provinceCode", biz.getProvinceId());
                    map.put("provinceName", biz.getProvinceName());
                    map.put("type", biz.getType());
                    map.put("newOrOld", biz.getRemark());
//                map.put("coopType", biz.getCoopType());
                });
            }
        }
        maps = maps.stream().filter(e -> ObjectUtils.isNotEmpty(e.get("provinceCode"))).collect(Collectors.toList());
        return maps;
    }

    public int getIntegerPartLength(BigDecimal number) {
        if (number.compareTo(BigDecimal.ZERO) == 0) {
            return 0;
        }
        String numStr = number.toPlainString();
        int dotIndex = numStr.indexOf('.');
        if (dotIndex == -1) {
            return numStr.length();
        }
        return dotIndex;
    }

    @Override
    public String getReportName() {
        return "ToB区域成交量地图";
    }
}
